<template>
  <view class="warehouse-container">
    <!-- 入库信息区域 -->
    <view class="info-section">
      <view class="section-header">
        <text class="section-title">单据信息</text>
      </view>
      <view class="info-form">
        <view class="form-item">
          <text class="form-label">单据日期</text>
          <picker
            class="form-picker"
            mode="date"
            :value="formData.ywDate"
            @change="handleDateChange"
          >
            <view class="picker-content">
              <text>{{ formData.ywDate }}</text>
              <text class="picker-arrow">></text>
            </view>
          </picker>
        </view>
        <view class="form-item">
          <text class="form-label">目标仓库</text>
          <picker
            class="form-picker"
            mode="selector"
            :range="warehouseOptions"
            range-key="label"
            :value="warehouseIndex"
            @change="handleWarehouseChange"
          >
            <view class="picker-content">
              <text>{{
                warehouseOptions[warehouseIndex]
                  ? warehouseOptions[warehouseIndex].label
                  : "请选择"
              }}</text>
              <text class="picker-arrow">></text>
            </view>
          </picker>
        </view>
        <view class="form-item">
          <text class="form-label">入库类型</text>
          <picker
            class="form-picker"
            mode="selector"
            :range="inStockTypeOptions"
            range-key="label"
            :value="inStockTypeIndex"
            @change="handleInStockTypeChange"
          >
            <view class="picker-content">
              <text>{{
                inStockTypeOptions[inStockTypeIndex]
                  ? inStockTypeOptions[inStockTypeIndex].label
                  : "请选择"
              }}</text>
              <text class="picker-arrow">></text>
            </view>
          </picker>
          <!-- 自动调拨按钮 - 仅在调拨入库时显示 -->
          <button
            v-if="
              inStockTypeOptions[inStockTypeIndex] &&
              inStockTypeOptions[inStockTypeIndex].value === '调拨入库'
            "
            class="auto-transfer-btn"
            :class="{ 'auto-transfer-btn-active': autoTransfer }"
            @click="toggleAutoTransfer"
          >
            {{ autoTransfer ? "已开启" : "自动调拨" }}
          </button>
        </view>
      </view>
    </view>

    <!-- 待入库区域 -->
    <view class="search-section">
      <view class="search-form">
        <view class="section-header">
          <view class="title-wrapper">
            <text class="section-title">待提交</text>
          </view>
          <!-- 统一输入框 -->
          <input
            ref="materialInput"
            v-model="searchForm.searchCode"
            class="material-input"
            type="text"
            placeholder="请扫码批次/计量秤"
            @keyup.enter="searchPackPrintRecords"
            @confirm="searchPackPrintRecords"
            :disabled="!inputMethodEnabled"
            autocomplete="off"
            spellcheck="false"
          />

          <button class="scan-btn" @click="searchPackPrintRecords">查询</button>
        </view>

        <!-- 提示文本和输入法开关在同一行 -->
        <view
          style="
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-top: 8rpx;
          "
        >
          <text class="section-subtitle" style="font-size: 24rpx; color: #999"
            >扫码获取当前待入库信息</text
          >

          <!-- 输入法开关 -->
          <view class="input-switch-container">
            <text class="switch-label"
              >输入法{{ inputMethodEnabled ? "开启" : "关闭" }}</text
            >
            <view
              class="custom-switch-wrapper"
              @click="handleInputMethodSwitchChange"
            >
              <view
                class="custom-switch"
                :class="{ 'custom-switch-active': inputMethodEnabled }"
              >
                <view
                  class="custom-switch-handle"
                  :class="{ 'custom-switch-handle-active': inputMethodEnabled }"
                ></view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 调拨出库列表（仅在调拨入库且非自动调拨时显示） -->
    <view
      class="search-section"
      v-if="formData.inStockType === '调拨入库' && !autoTransfer"
    >
      <view class="section-header">
        <text class="section-title">调拨出库列表</text>
        <view class="time-filter-buttons">
          <button
            class="filter-btn"
            :class="{ active: transferOutDateFilter === 'today' }"
            @tap="handleTransferOutDateChange('today')"
          >
            当日
          </button>
          <button
            class="filter-btn"
            :class="{ active: transferOutDateFilter === 'yesterday' }"
            @tap="handleTransferOutDateChange('yesterday')"
          >
            昨日
          </button>
          <button
            class="filter-btn"
            :class="{ active: transferOutDateFilter === 'week' }"
            @tap="handleTransferOutDateChange('week')"
          >
            近7天
          </button>
        </view>
      </view>

      <scroll-view
        class="table-scroll"
        scroll-y
        scroll-x
        v-if="transferOutList.length > 0"
      >
        <view class="table-scroll-container">
          <view class="table-scroll-wrapper">
            <view class="table-content">
              <view class="table-row header">
                <text class="table-cell">批次号</text>
                <text class="table-cell">钢种</text>
                <text class="table-cell">规格</text>
                <text class="table-cell">重量(KG)</text>
                <text class="table-cell">数量</text>
                <text class="table-cell">业务日期</text>
              </view>
              <view
                v-for="(item, index) in transferOutList"
                :key="index"
                class="table-row"
                @click="handleTransferOutRowClick(item)"
                style="cursor: pointer"
              >
                <text class="table-cell" :title="item.batchNo">{{
                  item.batchNo || "-"
                }}</text>
                <text class="table-cell" :title="item.mateialName">{{
                  item.steelGradeName || "-"
                }}</text>
                <text class="table-cell" :title="item.prodSpec">{{
                  item.prodSpec || "-"
                }}</text>
                <text class="table-cell">{{
                  (item.inWg || 0).toFixed(3)
                }}</text>
                <text class="table-cell">{{ item.inCount || 0 }}</text>
                <text class="table-cell">{{
                  dateHelperApi.formateTime(item.ywDate)
                }}</text>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>

      <view class="empty-state" v-else-if="!transferOutLoading">
        <text class="empty-text">暂无调拨出库记录</text>
      </view>

      <view class="loading-state" v-if="transferOutLoading">
        <text class="loading-text">加载中...</text>
      </view>
    </view>
    <!-- 待提交表格 -->
    <view class="material-table-section">
      <view class="table-body">
        <view class="table-row header">
          <view class="table-cell">选择</view>
          <view class="table-cell">入库重量</view>
          <view class="table-cell">入库数量</view>
          <view class="table-cell">工序</view>
          <view class="table-cell">批次号</view>
          <view class="table-cell">炉次号</view>
          <view class="table-cell">钢种</view>
          <view class="table-cell">规格</view>
          <view class="table-cell">库存重量</view>
          <view class="table-cell">库存数量</view>
        </view>
        <view
          v-for="(item, index) in packPrintRecords"
          :key="index"
          class="table-row"
          :class="{ selected: isRecordSelected(item) }"
          @click="toggleRecordSelection(item, index)"
        >
          <view class="table-cell">
            <text v-if="isRecordSelected(item)" class="check-icon">✓</text>
            <text v-else class="uncheck-icon">○</text>
          </view>
          <view class="table-cell quantity-cell">
            <input
              class="quantity-input large-input"
              type="digit"
              placeholder="入库重量"
              v-model="item.inWeight"
              @input="validateNumber(item, 'inWeight')"
            />
          </view>
          <view class="table-cell quantity-cell">
            <input
              class="quantity-input large-input"
              type="number"
              placeholder="入库数量"
              v-model="item.inQuantity"
              @input="validateNumber(item, 'inQuantity')"
            />
          </view>
          <view class="table-cell">{{ item.processName || "-" }}</view>
          <view class="table-cell">{{ item.batchNo || "-" }}</view>
          <view class="table-cell">{{ item.furnaceNo || "-" }}</view>
          <view class="table-cell">{{ item.steelGradeName || "-" }}</view>
          <view class="table-cell">{{ item.prodSpec || "-" }}</view>
          <view class="table-cell">{{ (item.scrapWg || 0).toFixed(3) }}</view>
          <view class="table-cell">{{ item.scrapeCount || 0 }}</view>
        </view>
      </view>
    </view>
    <view class="action-bar">
      <view class="action-row">
        <button class="btn-reset" @click="resetForm">重置</button>
        <button class="btn-submit" @click="handleManualSubmit">提交</button>
      </view>
    </view>
  </view>
</template>

<script>
// 导入API方法
import { ProdStockInApi } from "@/api/warehouse/prodstockin";
import { LzProdStockRealApi } from "@/api/warehouse/lzprodstockreal";
import { LzProdStockRecordApi } from "@/api/warehouse/lzprodstockrecord";
import { getProcessOptions } from "@/api/md/process";
// 导入PDA扫码功能
import { pdaScanApi } from "@/pages/smart/pdaScan";
// 导入日期格式化工具
import { dateHelperApi } from "@/pages/smart/warehouse/utils/date-helper";
// 导入数采计量功能
import { getDasKey } from "@/pages/smart/utils/das";

export default {
  name: "SemiStockIn",
  // 混入PDA扫码功能
  mixins: [pdaScanApi],
  data() {
    return {
      // 表单数据 - 按照数据列表字段重新定义
      formData: {
        inType: "manual", // 入库类型：transfer调拨入库, manual生产入库
        inDate: this.getCurrentDate(), // 入库日期
        ywDate: this.getCurrentDate(), // 业务日期
        warehouseId: "", // 仓库ID
        warehouseName: "", // 仓库名称
        remark: "", // 备注信息
        createBy: "", // 创建人
        createTime: "", // 创建时间
      },

      // 搜索表单
      searchForm: {
        searchCode: "",
      },

      // 查询参数
      queryParams: {
        batchNo: "", // 批次号
        furnaceNo: "", // 炉次号
        pageNum: 1,
        pageSize: 10,
      },

      // 输入法开关
      inputMethodEnabled: true,

      // 数据列表
      currentWarehouse: null,
      packPrintRecords: [], // 包装打印记录列表
      selectedRecords: [], // 选中的记录列表（支持多选）

      // 仓库选项 - 将从工序获取
      warehouseOptions: [],
      warehouseIndex: 0,

      // 入库方式选项
      inStockTypeOptions: [
        { label: "调拨入库", value: "调拨入库" },
        { label: "生产入库", value: "生产入库" },
        { label: "委外入库", value: "委外入库" },
      ],
      inStockTypeIndex: 0,

      // 炉次号相关数据
      furnaceTable: [], // 炉次号数据表格
      selectedFurnaceRecords: [], // 选中的炉次号记录

      // 自动调拨状态
      autoTransfer: false, // 是否开启自动调拨
      // 调拨出库列表相关状态
      transferOutList: [], // 调拨出库列表数据
      transferOutLoading: false, // 调拨出库列表加载状态
      transferOutQueryParams: {
        busStatus: "调拨出库",
        ywDateBegin: "",
        ywDateEnd: "",
        pageNum: 1,
        pageSize: 10,
      }, // 调拨出库查询参数
      transferOutDateFilter: "today", // 日期筛选：today、yesterday、week
    };
  },

  computed: {
    dateHelperApi() {
      return dateHelperApi;
    },
    // 计算选中记录的总重量
    totalWeight() {
      // 根据选中的记录计算总重量（入库重量）
      const total = this.selectedRecords.reduce(
        (sum, item) => sum + (Number(item.inWeight) || 0),
        0
      );
      return Number(total.toFixed(3));
    },
  },

  mounted() {
    try {
      // 1. 初始化日期为当前日期
      this.formData.inDate = this.getCurrentDate();
      this.formData.ywDate = this.getCurrentDate();

      // 2. 初始化入库类型（默认选择第一个）
      // if (this.inTypeOptions.length > 0) {
      //   this.inTypeIndex = 0;
      //   this.formData.inType = this.inTypeOptions[0].value;
      // }

      // 3. 初始化入库方式（默认选择第一个）
      if (this.inStockTypeOptions.length > 0) {
        this.inStockTypeIndex = 0;
        this.formData.inStockType = this.inStockTypeOptions[0].value;
      }

      // 4. 加载工序选项并初始化仓库
      this.loadProcessOptions();

      // 5. 初始化调拨出库列表（如果是调拨入库且非自动调拨）
      this.initTransferOutList();
    } catch (error) {
      console.error("加载初始数据失败:", error);
    }

    // 初始化输入法状态
    this.initInputMethod();

    // 启动PDA扫码（如果设备支持）
    this.startPdaContinuousScan();
  },

  beforeDestroy() {
    // 停止PDA扫码，释放资源
    this.stopPdaScan();
  },

  methods: {
    // 加载工序选项
    async loadProcessOptions() {
      try {
        const options = await getProcessOptions();
        this.warehouseOptions = options.map((item) => ({
          label: item.text,
          value: item.text,
        }));
        console.log("工序选项加载成功:", this.warehouseOptions);

        // 加载完工序后初始化仓库
        if (this.warehouseOptions.length > 0) {
          this.initializeWarehouse();
        }
      } catch (error) {
        console.error("加载工序选项失败:", error);
        this.warehouseOptions = [];
      }
    },
    // 打印测试
    async handlePdaPrint() {
      try {
        console.log("开始打印测试...");

        const result = this.pdaPrint(
          "B20251019",
          "测试备注1",
          "备注2",
          "备注3"
        );

        if (result) {
          this.$modal.alert({
            content: "打印成功",
            title: "提示",
          });
        } else {
          this.$modal.alert({
            content: "打印失败，请检查打印机状态",
            title: "错误",
          });
        }
      } catch (error) {
        console.error("打印测试异常:", error);
        this.$modal.alert({
          content: "打印测试异常：" + error.message,
          title: "错误",
        });
      }
    },
    /**
     * 获取当前是否为自动提交模式
     * 规则：
     * - 任何模式下达到5笔都会触发自动提交
     */
    getIsAutoSubmitMode() {
      return true;
    },

    // 获取当前日期时间（年月日时分秒）
    getCurrentDate() {
      const date = new Date();
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    // 初始化仓库
    initializeWarehouse() {
      try {
        // 检查是否有工序选项
        if (this.warehouseOptions.length === 0) {
          console.warn("工序选项为空，无法初始化仓库");
          return;
        }

        // 从Vuex store获取用户配置的仓库信息
        const userConfig = this.$store.state.user.userConfig;
        if (userConfig && userConfig.wmName) {
          // 如果用户有配置仓库，使用配置的仓库
          const warehouseName = userConfig.wmName;
          const warehouseIndex = this.warehouseOptions.findIndex(
            (item) => item.value === warehouseName
          );

          if (warehouseIndex !== -1) {
            this.warehouseIndex = warehouseIndex;
          } else {
            this.warehouseIndex = 0; // 默认选择第一个
          }
        } else {
          // 默认选择第一个仓库
          this.warehouseIndex = 0;
        }

        // 设置当前仓库信息
        const selectedWarehouse = this.warehouseOptions[this.warehouseIndex];
        this.currentWarehouse = {
          warehouseName: selectedWarehouse.value,
          warehouseId: selectedWarehouse.value,
        };

        // 更新formData中的仓库信息
        this.formData.warehouseId = selectedWarehouse.value;
        this.formData.warehouseName = selectedWarehouse.value;

        console.log("仓库初始化完成:", this.currentWarehouse);
      } catch (error) {
        console.error("初始化仓库失败:", error);
        // 出错时默认选择第一个仓库
        this.warehouseIndex = 0;
        if (this.warehouseOptions.length > 0) {
          const selectedWarehouse = this.warehouseOptions[0];
          this.currentWarehouse = {
            warehouseName: selectedWarehouse.value,
            warehouseId: selectedWarehouse.value,
          };
          this.formData.warehouseId = selectedWarehouse.value;
          this.formData.warehouseName = selectedWarehouse.value;
        }
      }
    },

    // 初始化输入法状态
    initInputMethod() {
      // 从本地存储读取输入法状态
      const saved = uni.getStorageSync("inputMethodEnabled");
      if (saved !== null && saved !== undefined) {
        this.inputMethodEnabled = saved;
      }
    },

    /**
     * 处理扫码结果
     * @param {string} barcode - 扫码得到的条码内容
     */
    handleScanResult(barcode) {
      console.log("【扫码处理】收到扫码结果:", barcode);
      // 将扫码结果赋值给搜索框
      this.searchForm.searchCode = barcode;

      // 如果扫码值不是DAS开头，则赋值给批次号查询条件
      if (!barcode.startsWith("DAS")) {
        this.queryParams.batchNo = barcode;
        this.queryParams.furnaceNo = "";
      }

      // 自动执行查询
      this.searchPackPrintRecords();
    },

    // 清除原表格中的选中状态
    clearOriginalTableSelection() {
      this.materialTable.forEach((item) => {
        if (item.isCheck) {
          this.$set(item, "isCheck", false);
          this.$set(item, "showError", false);
          this.$set(item, "prod_count", 0);
          this.$set(item, "trans_count", 0);
        }
      });
    },

    // 日期变更
    handleDateChange(e) {
      // 获取选择的日期
      const selectedDate = e.detail.value;
      // 获取当前时间，保持时分秒
      const now = new Date();
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      const seconds = String(now.getSeconds()).padStart(2, "0");
      // 组合成完整的日期时间格式
      this.formData.ywDate = `${selectedDate} ${hours}:${minutes}:${seconds}`;
    },

    // 仓库变更
    handleWarehouseChange(e) {
      const index = parseInt(e.detail.value);
      this.warehouseIndex = index;

      if (
        this.warehouseOptions &&
        this.warehouseOptions.length > 0 &&
        index >= 0
      ) {
        const selectedWarehouse = this.warehouseOptions[index];
        this.currentWarehouse = {
          warehouseName: selectedWarehouse.value,
          warehouseId: selectedWarehouse.value,
        };
        // 更新formData中的仓库信息
        this.formData.warehouseId = selectedWarehouse.value;
        this.formData.warehouseName = selectedWarehouse.value;

        console.log("仓库变更完成:", this.currentWarehouse);
      }

      // 清空当前数据
      this.packPrintRecords = [];
      this.selectedRecords = [];
      this.furnaceTable = [];
      this.selectedFurnaceRecords = [];
    },

    // 入库方式变更
    handleInStockTypeChange(e) {
      const index = parseInt(e.detail.value);
      this.inStockTypeIndex = index;
      // 更新formData中的入库方式
      if (
        this.inStockTypeOptions &&
        this.inStockTypeOptions.length > 0 &&
        index >= 0
      ) {
        this.formData.inStockType = this.inStockTypeOptions[index].value;
        console.log("入库方式变更:", this.formData.inStockType);

        // 如果是调拨入库且非自动调拨，加载调拨出库列表
        if (this.formData.inStockType === "调拨入库" && !this.autoTransfer) {
          this.loadTransferOutList();
        }
      }
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        searchCode: "",
      };
      this.packPrintRecords = [];
    },

    // 数字校验
    validateNumber(record, field) {
      const value = record[field];
      if (value === "" || value === null || value === undefined) {
        return;
      }

      const numValue = Number(value);
      if (isNaN(numValue) || numValue < 0) {
        this.$modal.alert({
          content: `${
            field === "inWeight" ? "入库重量" : "入库数量"
          }必须是有效数字`,
          title: "输入错误",
        });
        record[field] = "";
        return;
      }

      // 保留3位小数
      if (field === "inWeight") {
        record[field] = Number(numValue.toFixed(3));
      } else {
        record[field] = Math.floor(numValue);
      }
    },

    // 聚焦到输入框（输入法开启时弹出键盘）
    focusInput() {
      if (this.inputMethodEnabled && this.$refs.materialInput) {
        this.$nextTick(() => {
          if (this.$refs.materialInput.focus) {
            this.$refs.materialInput.focus();
          }
        });
      }
    },

    // 输入法开关切换处理
    handleInputMethodSwitchChange() {
      this.inputMethodEnabled = !this.inputMethodEnabled;

      // 保存到本地存储
      uni.setStorageSync("inputMethodEnabled", this.inputMethodEnabled);

      // 如果开启输入法，聚焦输入框
      if (this.inputMethodEnabled) {
        this.focusInput();
        // 停止PDA扫码
        this.stopPdaScan();
      } else {
        // 如果关闭输入法，启动PDA扫码
        this.startPdaContinuousScan();
      }
    },

    /**
     * 启动PDA连续扫码
     * 在输入法关闭时启用PDA扫码，开启时使用输入法
     */
    startPdaContinuousScan() {
      // 只有在输入法关闭时才启用PDA扫码
      if (!this.inputMethodEnabled) {
        const success = this.startPdaScan((barcode) => {
          // 扫码结果处理
          this.handleScanResult(barcode);
        });

        if (success) {
          console.log("PDA连续扫码已启动");
        } else {
          console.warn("PDA扫码启动失败，将使用手动输入模式");
        }
      }
    },

    // 搜索包装打印记录11
    async searchPackPrintRecords() {
      try {
        uni.showLoading({ title: "查询中..." });

        // 构建查询参数
        const params = {
          pageNum: 1,
          pageSize: 10,
        };

        // 将扫码结果赋值给搜索框
        const barcode = this.searchForm.searchCode;

        if (barcode.startsWith("DAS")) {
          try {
            // 获取数采计量数据
            const dasResult = await getDasKey(barcode);
            if (
              dasResult &&
              dasResult.code === 0 &&
              dasResult.result &&
              dasResult.result.length > 0
            ) {
              // 解析重量值
              const weightValue = parseFloat(dasResult.result[0].v);
              if (!isNaN(weightValue)) {
                // 如果没有选中行，则默认赋值到第一行；如果有选中行，则赋值到选中行的入库重量列
                let targetRecord = null;

                if (this.selectedRecords.length > 0) {
                  // 有选中行，使用最后一个选中的记录
                  targetRecord =
                    this.selectedRecords[this.selectedRecords.length - 1];
                } else if (this.packPrintRecords.length > 0) {
                  // 没有选中行，默认使用第一行
                  targetRecord = this.packPrintRecords[0];
                } else {
                  uni.showToast({
                    title: "没有可复制的入库单据，请先查询",
                    icon: "none",
                  });
                  return;
                }

                if (targetRecord) {
                  // 使用 $set 确保响应式更新
                  this.$set(targetRecord, "inWeight", weightValue.toFixed(3));
                }
                uni.showToast({
                  title: `获取计量数据成功：${weightValue}KG`,
                  icon: "success",
                });
              } else {
                console.warn("数采数据格式不正确，无法解析重量值");
              }
            } else {
              console.warn("未找到数采计量数据或数据格式不正确");
            }
          } catch (dasError) {
            console.error("获取数采计量数据失败:", dasError);
            // 数采失败不影响主流程，继续执行
          }
          return;
        }

        // 解析扫码结果：按第一个"-"拆分
        const parts = barcode.split("-");
        if (parts.length >= 2) {
          const a = parts[0];
          const b = parts[1];

          // 判断b中是否包含字母
          const hasLetter = /[a-zA-Z]/.test(b);
          if (hasLetter) {
            // 批次号
            this.queryParams.batchNo = barcode;
            delete this.queryParams.furnaceNo;
          } else {
            // 炉次号
            this.queryParams.furnaceNo = barcode;
            delete this.queryParams.batchNo;
          }
        }
        // 根据扫码解析结果设置查询参数
        if (this.queryParams.batchNo) {
          params.batchNo = this.queryParams.batchNo;
        } else if (this.queryParams.furnaceNo) {
          params.furnaceNo = this.queryParams.furnaceNo;
        } else {
          // 默认使用搜索框内容作为炉次号查询
          params.furnaceNo = this.searchForm.searchCode;
        }
        console.log("查询参数:", params);

        // 其他仓库使用普通查询
        const response = await LzProdStockRealApi.getLzProdStockRealPage(
          params
        );
        if (response.code === 0) {
          this.packPrintRecords = response.data.list || [];
          uni.showToast({
            title: "查询成功" + this.packPrintRecords.length + "条记录",
            icon: "none",
          });

          // 如果扫码值不是DAS开头且有查询结果，默认选中第一条数据
          if (!barcode.startsWith("DAS") && this.packPrintRecords.length > 0) {
            this.toggleRecordSelection(this.packPrintRecords[0], 0);
          }
        } else {
          uni.showToast({
            title: response.msg || "查询失败",
            icon: "none",
          });
        }

        // 查询完成后清空输入框，便于下次输入
        this.searchForm.searchCode = "";
        // 清空查询参数
        this.queryParams.batchNo = "";
        this.queryParams.furnaceNo = "";

        // 重新聚焦到输入框
        this.$nextTick(() => {
          if (this.inputMethodEnabled) {
            this.focusInput();
          }
        });
      } catch (error) {
        console.error("查询失败:", error);
        uni.showToast({
          title: "查询失败，请重试",
          icon: "none",
        });
      } finally {
        uni.hideLoading();
      }
    },

    // 判断记录是否被选中
    isRecordSelected(record) {
      return this.selectedRecords.some((item) => item.id === record.id);
    },

    // 切换记录选中状态
    toggleRecordSelection(record, index) {
      console.log("【手动选中】切换记录选中状态，记录ID:" + record.id);

      const existingIndex = this.selectedRecords.findIndex(
        (item) => item.id === record.id
      );

      if (existingIndex !== -1) {
        // 如果已选中，则取消选中
        console.log(
          "【手动选中】取消选中记录，当前选中数:" +
            (this.selectedRecords.length - 1)
        );
        this.selectedRecords.splice(existingIndex, 1);
      } else {
        // 否则添加到选中列表
        console.log(
          "【手动选中】添加选中记录，当前选中数:" +
            (this.selectedRecords.length + 1)
        );
        this.selectedRecords.push({ ...record });

        // 检查是否达到5条数据，如果是则自动提交
        if (this.selectedRecords.length === 5) {
          console.log("【手动选中】达到5条记录，准备自动提交");
          // 延迟一下再自动提交，让用户能看到选择效果
          setTimeout(() => {
            console.log("【手动选中】延迟结束，开始自动提交");
            this.autoSubmitForm();
          }, 500);
        }
      }
    },

    // 判断炉次号记录是否被选中
    isFurnaceRecordSelected(record) {
      return this.selectedFurnaceRecords.some(
        (item) => item.furnaceNo === record.furnaceNo
      );
    },

    // 切换炉次号记录选中状态
    toggleFurnaceRecordSelection(record) {
      console.log(
        "【炉次号选中】切换炉次号记录选中状态，炉次号:" + record.furnaceNo
      );

      const existingIndex = this.selectedFurnaceRecords.findIndex(
        (item) => item.furnaceNo === record.furnaceNo
      );

      if (existingIndex !== -1) {
        // 如果已选中，则取消选中
        console.log(
          "【炉次号选中】取消选中炉次号记录，当前选中数:" +
            (this.selectedFurnaceRecords.length - 1)
        );
        this.selectedFurnaceRecords.splice(existingIndex, 1);
      } else {
        // 否则添加到选中列表
        console.log(
          "【炉次号选中】添加选中炉次号记录，当前选中数:" +
            (this.selectedFurnaceRecords.length + 1)
        );
        this.selectedFurnaceRecords.push({ ...record });
      }
    },

    // 调拨出库单行点击事件 - 将选中行的重量和数量赋值到待提交列表第一行
    handleTransferOutRowClick(transferOutItem) {
      console.log("【调拨出库行点击】选中调拨出库记录:", transferOutItem);

      if (!transferOutItem) {
        return;
      }

      // 如果有待提交记录，将重量和数量赋值到第一行
      if (this.packPrintRecords.length > 0) {
        const firstRecord = this.packPrintRecords[0];

        // 设置入库重量（调拨出库的重量）
        if (transferOutItem.inWg) {
          this.$set(firstRecord, "inWeight", transferOutItem.inWg.toFixed(3));
        }

        // 设置入库数量（调拨出库的数量）
        if (transferOutItem.inCount) {
          this.$set(firstRecord, "inQuantity", transferOutItem.inCount);
        }

        // 自动选中第一行
        this.toggleRecordSelection(firstRecord, 0);

        uni.showToast({
          title: "已填充调拨出库数据到第一行",
          icon: "success",
        });

        console.log("【调拨出库行点击】已赋值到第一行:", {
          inWeight: firstRecord.inWeight,
          inQuantity: firstRecord.inQuantity,
        });
      } else {
        uni.showToast({
          title: "暂无待提交记录",
          icon: "none",
        });
      }
    },

    // 删除炉次号记录
    deleteFurnaceRecord(index) {
      console.log("【炉次号删除】删除炉次号记录，索引:" + index);

      // 先从选中列表中移除（在删除数组元素之前获取记录）
      const record = this.furnaceTable[index];
      if (record) {
        const selectedIndex = this.selectedFurnaceRecords.findIndex(
          (item) => item.furnaceNo === record.furnaceNo
        );
        if (selectedIndex !== -1) {
          this.selectedFurnaceRecords.splice(selectedIndex, 1);
        }
      }

      // 最后删除表格中的记录
      this.furnaceTable.splice(index, 1);
    },

    // 处理手动提交按钮点击
    handleManualSubmit() {
      console.log("【手动提交】用户点击提交入库按钮");
      // 手动提交模式下，isAutoSubmit为false
      this.submitForm(false);
    },

    // 切换自动调拨状态
    toggleAutoTransfer() {
      this.autoTransfer = !this.autoTransfer;
      console.log(`自动调拨状态: ${this.autoTransfer ? "开启" : "关闭"}`);

      // 显示状态提示
      uni.showToast({
        title: this.autoTransfer ? "已开启自动调拨" : "已关闭自动调拨",
        icon: "none",
        duration: 1500,
      });

      // 如果关闭自动调拨且当前是调拨入库，重新加载调拨出库列表
      if (!this.autoTransfer && this.formData.inStockType === "调拨入库") {
        this.loadTransferOutList();
      }
    },

    // 重置表单
    resetForm() {
      // 重置formData到初始状态
      this.formData = {
        inType: "manual", // 保持入库类型不变
        inDate: this.getCurrentDate(),
        ywDate: this.getCurrentDate(),
        warehouseId: this.currentWarehouse
          ? this.currentWarehouse.warehouseId
          : "",
        warehouseName: this.currentWarehouse
          ? this.currentWarehouse.warehouseName
          : "",
        remark: "",
        createBy: "",
        createTime: "",
      };

      // 重置搜索和相关数据
      this.resetSearch();

      console.log("表单已重置");
    },

    /**
     * 提交表单
     * @param {boolean} isAutoSubmit - 是否为自动提交
     *  - true: 自动提交（达到5笔数据时触发）
     *  - false: 手动提交（用户点击提交按钮触发）
     */
    async submitForm(isAutoSubmit = false) {
      try {
        // 表单验证
        const validation = this.validateForm();
        if (!validation.valid) {
          uni.showToast({
            title: validation.message,
            icon: "none",
          });
          return;
        }

        // 检查是否所有选中的记录都填写了入库重量和数量
        const invalidRecords = this.selectedRecords.filter((record) => {
          return (
            !this.isValidNumber(record.inWeight) &&
            !this.isValidNumber(record.inQuantity)
          );
        });

        if (invalidRecords.length > 0) {
          uni.showToast({
            title: "请填写所有记录的入库重量或数量",
            icon: "none",
          });
          return;
        }

        // 如果不是自动提交，显示确认对话框
        if (!isAutoSubmit) {
          const confirmed = await this.showSubmitConfirm();
          if (!confirmed) {
            console.log("用户取消提交");
            return;
          }
        }

        // 调拨入库特殊判断：检查待提交数据的busStatus是否是调拨出库
        const currentInStockType =
          this.inStockTypeOptions[this.inStockTypeIndex].value;
        if (currentInStockType === "调拨入库") {
          // 检查所有选中的记录，确保它们的busStatus是"调拨出库"
          const invalidTransferRecords = this.selectedRecords.filter(
            (record) => {
              return record.busStatus !== "调拨出库";
            }
          );

          if (invalidTransferRecords.length > 0 && !this.autoTransfer) {
            const batchNos = invalidTransferRecords
              .map((record) => record.batchNo)
              .join(", ");
            uni.showToast({
              title: `批次${batchNos}尚未调拨出库，请联系相关人员确认`,
              icon: "none",
              duration: 3000,
            });
            return;
          }
        }

        uni.showLoading({ title: "提交中..." });

        // 构建提交数据
        const submitData = {
          stockInList: this.selectedRecords.map((record) => ({
            id: record.id,
            inDate: this.formData.ywDate,
            scrapWg: Number(record.inWeight),
            scrapCount: Number(record.inQuantity),
            processName: this.warehouseOptions[this.warehouseIndex].value,
            busStatus: this.autoTransfer
              ? "自动调拨"
              : this.inStockTypeOptions[this.inStockTypeIndex].value,
            recordType: "入库",
            batchNo: record.batchNo,
            furnaceNo: record.furnaceNo,
            steelGradeName: record.steelGradeName,
            prodSpec: record.prodSpec,
          })),
        };

        // 调用submitSemiStockIn方法
        const response = await LzProdStockRealApi.submitSemiStockIn(submitData);

        if (response.code === 0) {
          await this.handleSubmitSuccess(response);
        } else {
          uni.showToast({
            title: response.msg || "提交失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("提交失败:", error);
        uni.showToast({
          title: "提交失败，请重试",
          icon: "none",
        });
      } finally {
        uni.hideLoading();
      }
    },

    // 提交半成品入库单
    async submitSemiStockIn(data) {
      // 调用真实的 API：ProdStockInApi.createSemiStockIn
      return await ProdStockInApi.createSemiStockIn(data);
    },

    // 表单验证
    validateForm() {
      if (!this.formData.warehouseName) {
        return { valid: false, message: "请选择仓库" };
      }

      if (!this.formData.inDate) {
        return { valid: false, message: "请选择入库日期" };
      }

      if (this.selectedRecords.length === 0) {
        return { valid: false, message: "请选择要入库的记录" };
      }

      return { valid: true };
    },

    // 验证数字有效性
    isValidNumber(value) {
      return (
        value !== null &&
        value !== undefined &&
        !isNaN(value) &&
        isFinite(value)
      );
    },

    // 显示提交确认
    showSubmitConfirm() {
      return new Promise((resolve) => {
        const recordCount = this.selectedRecords.length;
        const totalWeight = this.totalWeight;

        uni.showModal({
          title: "确认提交",
          content: `共${recordCount}条记录，总重量：${totalWeight}KG，是否确认提交入库？`,
          confirmText: "确认",
          cancelText: "取消",
          success: (res) => {
            resolve(res.confirm);
          },
        });
      });
    },

    // 处理提交成功
    async handleSubmitSuccess(res) {
      uni.showToast({
        title: "入库单创建成功",
        icon: "success",
        duration: 2000,
      });

      // 记录成功日志
      console.log("入库单创建成功:", res.data);

      // 重置表单
      this.resetForm();
    },

    // 初始化调拨出库列表
    async initTransferOutList() {
      // 只有在调拨入库且非自动调拨状态下才加载
      if (this.formData.inStockType === "调拨入库" && !this.autoTransfer) {
        this.setTransferOutDateRange();
        await this.loadTransferOutList();
      }
    },

    // 设置调拨出库日期范围（仅用于初始化）
    setTransferOutDateRange() {
      // 使用通用的updateDateRange函数初始化日期范围
      const result = dateHelperApi.updateDateRange(this.transferOutDateFilter, {
        callback: ({ startDate, endDate }) => {
          // 更新查询参数的日期范围
          this.transferOutQueryParams.ywDateBegin = startDate;
          this.transferOutQueryParams.ywDateEnd = endDate;
        },
      });
    },

    // 格式化日期为YYYY-MM-DD
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },

    // 加载调拨出库列表
    async loadTransferOutList() {
      try {
        this.transferOutLoading = true;

        // 设置日期范围
        this.setTransferOutDateRange();

        // 构建查询参数
        const params = {
          ...this.transferOutQueryParams,
          pageNum: 1, // 重置为第一页
        };

        // 如果存在日期范围，使用数组格式
        if (
          this.transferOutQueryParams.ywDateBegin &&
          this.transferOutQueryParams.ywDateEnd
        ) {
          params.ywDate = [
            this.transferOutQueryParams.ywDateBegin,
            this.transferOutQueryParams.ywDateEnd,
          ];
          // 移除单独的日期参数
          delete params.ywDateBegin;
          delete params.ywDateEnd;
        }

        console.log("调拨出库查询参数:", params);

        // 调用API查询
        const response = await LzProdStockRecordApi.getLzProdStockRecordPage(
          params
        );

        if (response.code === 0) {
          this.transferOutList = response.data?.list || [];
          console.log("调拨出库列表加载成功:", this.transferOutList);
        } else {
          uni.showToast({
            title: response.msg || "加载调拨出库列表失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("加载调拨出库列表失败:", error);
        uni.showToast({
          title: "加载调拨出库列表失败",
          icon: "none",
        });
      } finally {
        this.transferOutLoading = false;
      }
    },

    // 处理调拨出库日期筛选变更
    handleTransferOutDateChange(filter) {
      console.log(
        "日期筛选变更:",
        filter,
        "当前筛选:",
        this.transferOutDateFilter
      );

      // 如果点击的是当前已选中的筛选，不重复加载
      if (this.transferOutDateFilter === filter) {
        console.log("重复点击相同筛选，不重新加载");
        return;
      }

      this.transferOutDateFilter = filter;

      // 使用通用的updateDateRange函数设置日期范围
      const result = dateHelperApi.updateDateRange(filter, {
        callback: ({ startDate, endDate }) => {
          // 更新查询参数的日期范围
          this.transferOutQueryParams.ywDateBegin = startDate;
          this.transferOutQueryParams.ywDateEnd = endDate;

          // 加载数据
          this.loadTransferOutList();
        },
      });
    },
  },
};
</script>

<style lang="scss">
@import "~@/pages/smart/scss/create.scss";

// 自动调拨按钮样式
.auto-transfer-btn {
  margin-left: 20rpx;
  padding: 8rpx 16rpx;
  font-size: 24rpx;
  border: 2rpx solid #dcdfe6;
  border-radius: 8rpx;
  background-color: #ffffff;
  color: #606266;
  min-width: 120rpx;
  text-align: center;
  transition: all 0.3s ease;

  &:active {
    opacity: 0.8;
  }
}

// 自动调拨按钮激活状态
.auto-transfer-btn-active {
  background-color: #409eff;
  border-color: #409eff;
  color: #ffffff;
}

// 表单项目样式调整，确保按钮和选择器在同一行
.form-item {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .form-picker {
    flex: 1;
    margin-right: 10rpx;
  }
}

// 调拨出库列表使用通用样式，不再定义专用样式

.transfer-out-section .loading-text {
  font-size: 28rpx;
  color: #409eff;
}
</style>
